package cn.fbs.service;

import cn.fbs.dao.dm.DMDataInfoMapper;
import cn.fbs.dao.dm.DMImageInfoMapper;
import cn.fbs.dao.dm.DMVideoInfoMapper;
import cn.fbs.model.TDataInfo;
import cn.fbs.model.TImageInfo;
import cn.fbs.model.TVideoInfo;
import cn.fbs.util.DownloadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.File;


@Service
public class DownLoadService {
    @Value("${resource.locations}")
    private String resourceLocations;

    @Autowired
    private DMImageInfoMapper imageInfoMapper;
    @Autowired
    private DMVideoInfoMapper videoInfoMapper;
    @Autowired
    private DMDataInfoMapper dataInfoMapper;

    public void fileDown(HttpServletResponse response, String fileUrl) {
           File file = new File(resourceLocations + fileUrl);
        /**
         * 若下载，则修改文件的下载次数字段
         */
        if (fileUrl.startsWith("upload/img")) {
            TImageInfo imageInfo = imageInfoMapper.getImageByFileUrl(fileUrl);
            if (imageInfo != null) {
                imageInfo.setDownloads(imageInfo.getDownloads() + 1);
                imageInfoMapper.updateByPrimaryKeySelective(imageInfo);
            }

        }
        if (fileUrl.startsWith("upload/video")) {
            TVideoInfo videoInfo = videoInfoMapper.getVideoByFileUrl(fileUrl);
            if (videoInfo != null) {
                videoInfo.setDownloads(videoInfo.getDownloads() + 1);
                videoInfoMapper.updateByPrimaryKeySelective(videoInfo);
            }
        }
        if (fileUrl.startsWith("upload/data")) {

            TDataInfo dataInfo = dataInfoMapper.getDataByFileUrl(fileUrl);
            if (dataInfo != null) {
                dataInfo.setDownloads(dataInfo.getDownloads() + 1);
                dataInfoMapper.updateByPrimaryKeySelective(dataInfo);
            }
        }

        DownloadUtil.download(file, response);
    }


}
